﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace AndroidEditor.Unit
{
    class XmlUnit
    {
        public static System.Xml.XmlNode GetRoot(System.Xml.XmlDocument xmldoc)
        {
            if (xmldoc.HasChildNodes)
            {
                return xmldoc.ChildNodes[0];
            }
            else
            {
                XmlNode root = xmldoc.CreateNode(XmlNodeType.Element, "Root", "");
                xmldoc.AppendChild(root);
                return root;
            }
        }

        public static System.Xml.XmlNode FindNodeOrCreateNew(System.Xml.XmlNode root, string value)
        {
            foreach (XmlNode node in root.ChildNodes)
            {
                if (node.Name == value)
                {
                    return node;
                }
            }
            XmlNode n = root.OwnerDocument.CreateNode(XmlNodeType.Element, value, "");
            root.AppendChild(n);
            return n;
        }

        public static XmlAttribute FindAttributeOrCreateNew(XmlNode node, string value)
        {
            foreach (XmlAttribute attributeItem in node.Attributes)
            {
                if (attributeItem.Name == value)
                {
                    return attributeItem;
                }
            }
            XmlAttribute attribute = node.OwnerDocument.CreateAttribute(value);
            node.Attributes.Append(attribute);
            return attribute;
        }

        public static XmlNode FindOrCreateNewNodeWithValue(XmlNode root, string NodeName, string AttriName, string value)
        {
            foreach (XmlNode node in root.ChildNodes)
            {
                if (node.Name == NodeName && FindAttributeOrCreateNew(node, AttriName).Value == value)
                {
                    return node;
                }
            }
            XmlNode n = root.OwnerDocument.CreateNode(XmlNodeType.Element, NodeName, "");
            root.AppendChild(n);
            XmlAttribute attribute = FindAttributeOrCreateNew(n, AttriName);
            attribute.Value = value;
            return n;
        }
    }
}
